package com.acme.Applications;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.BankDataLoaderService;
import com.acme.domain.bank.BankService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class Server {
    public  static  void main(String... args) {
        Bank bank = new Bank();
        BankService service = bank.getService();
        service.readBank(args.length > 0 ? args[0] : "bank.res");

        System.out.println("Wutzupguys? ITS BAAAAAAAAAAANK SERVER!\n AaaAaAnd we r listening port 666");

        try (ServerSocket ss = new ServerSocket(666);
             Socket socket = ss.accept()) {
            try (DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                 DataInputStream in = new DataInputStream(socket.getInputStream())) {
                StringTokenizer st;
                BankDataLoaderService bdls = new BankDataLoaderService();
                work: while (true) {
                    st = new StringTokenizer(in.readUTF(), " ");
                    switch (st.nextToken()) {
                        case "add":
                            service.addClient(bdls.parseClient(st.nextToken()));
                            break;
                        case "get":
                            out.writeUTF(bank.toString());
                            break;
                        case "end":
                            out.writeUTF("end");
                            break work;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                System.err.println("DATASTREAMEXCEPTION!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
